#!/bin/python3
# 打开 .vscode/c_cpp_properties.json 找到 defines数组，判断传入的"arg[1]"字符串是否属于该数组的某个字符串的子串，如果是则将arg[2]替换进去，如果不是则将arg在则添加arg[2]

import json
import sys
def clear_define_in_json(file_path):
    # 读取 JSON 文件
    with open(file_path, 'r') as file:
        data = json.load(file)

    # 遍历 configurations 数组
    for config in data.get("configurations", []):
        defines = config.get("defines", [])
        deffines_clear = []
        config["defines"] = deffines_clear  # 更新回配置中

    # 将修改后的内容写回文件
    with open(file_path, 'w') as file:
        json.dump(data, file, indent=4)

def update_define_in_json(file_path, key, new_value):
    # 读取 JSON 文件
    with open(file_path, 'r') as file:
        data = json.load(file)

    # 遍历 configurations 数组
    for config in data.get("configurations", []):
        defines = config.get("defines", [])

        found = False
        for i, define in enumerate(defines):
            if key in define:  # 判断 key 是否是 define 的子串
                # new_value 为空时删除该define
                if new_value == "":
                    del defines[i]
                    break
                defines[i] = new_value  # 替换为新值
                found = True
                break

        if not found:
            defines.append(new_value)  # 如果没有找到，添加新值

        config["defines"] = defines  # 更新回配置中

    # 将修改后的内容写回文件
    with open(file_path, 'w') as file:
        json.dump(data, file, indent=4)

if __name__ == "__main__":
    if len(sys.argv) != 3:
        print("Usage: python set_defines_vscode_properties.py <file_path> <config_path>")
        sys.exit(1)

    file_path = sys.argv[1]
    # 清除file_path json 文件的 configurations 下的 defines
    clear_define_in_json(file_path)

    config_path = sys.argv[2]
    # 按行读取config_path 文件的内容，只存CONFIG_开头的子串
    with open(config_path, 'r') as file:
        lines = file.readlines()
        for line in lines:
            if line.startswith("CONFIG_"):
                # 判断是否存在"\""
                if "\"" in line:
                    # 删除所有"\""
                    line = line.replace("\"", "")
                    key = line[len("CONFIG_"):line.index("=")]
                    new_value = line[len("CONFIG_"):]
                    new_value = new_value.replace("\n", "")
                    update_define_in_json(file_path, key, new_value)
                else:
                    # 判断"="之后的字符串是否为"y"
                    if line[line.index("=") + 1:].strip() == "y":
                        key = line[len("CONFIG_"):line.index("=")]
                        new_value = key+"=1"
                        update_define_in_json(file_path, key, new_value)
                    else:
                        key = line[len("CONFIG_"):line.index("=")]
                        new_value = key+"=0"
                        update_define_in_json(file_path, key, new_value)

    

